/* 
 * Copyright (C) 2012 UTSChedule
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package utsc.apps.utschedule.ui;

import utsc.apps.utschedule.R;
import utsc.apps.utschedule.util.Validator;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockDialogFragment;

/**
 * This dialog fragment is a fully reusable component with various customisable
 * interface callback.
 * 
 */
public class InputDialogFragment extends SherlockDialogFragment {
	
	/**
	 * This interface delegates the interface setup and action handling logics
	 * to its parent activity.
	 * 
	 */
	public interface OnInputListener{
		/**
		 * Setup the input views for the dialog
		 * @param v the inflated content input view
		 */
		public void setupInputs(View v);
		/**
		 * Setup the action when the save button is clicked
		 * @param v the inflated content input view
		 */
		public void onInputSaveListener(View v);
	}
	
	/**
	 * This interface delegates the list item action handling logic to its
	 * parent activity.
	 * 
	 */
	public interface OnListItemSelectedListener{
		public void	onListItemSelected(int position, String item);
	}
	
	private String _title;
	private int _contentviewResId;
	private String _saveBtnLabel;
	private String _cancelBtnLabel;
	private String[] _listEntries;
	private boolean _isListDialog=false;
	private boolean _positiveBtnOnly=false;
	private String _confirmMessage;
	private static final String ARGS_TITLE="title";
	private static final String ARGS_CONTENT_RES_ID="contentviewResId";
	private static final String ARGS_SAVE_BTN_LABEL="saveBtnLabel";
	private static final String ARGS_CANCEL_BTN_LABEL="cancelBtnLabel";
	public static final String TAG="utsc.apps.utschedule.ui.InputDialogFragment";
	private static final String ARGS_LIST_ENTRIES="listEntries";
	private static final String ARGS_LIST_DIALOG="listDialog";
	private static final String ARGS_CONFIRM_MESSAGE="confirmMessage";
	private static final String ARGS_POSITIVE_BTN_ONLY="positiveBtnOnly";
	
	/**
	 * This constructor initializes a new input dialog by taking the given
	 * dialog title, dialog interface resource id, and a custom save button
	 * label.
	 * 
	 * @param title
	 * @param contentviewResId
	 * @param saveBtnLabel
	 * @return a basic input dialog with a custom save label
	 */
	public static InputDialogFragment newInstance(String title, int contentviewResId,String saveBtnLabel){
		if (contentviewResId==0) {
			throw new IllegalArgumentException("Missing Content View Resource");
		}
		Bundle args=new Bundle();
		args.putString(ARGS_TITLE, title);
		args.putInt(ARGS_CONTENT_RES_ID, contentviewResId);
		args.putString(ARGS_SAVE_BTN_LABEL, saveBtnLabel);
		InputDialogFragment fragment=new InputDialogFragment();
		fragment.setArguments(args);
		return fragment;
	}
	
	/**
	 * This constructor initializes a new input dialog by taking the given
	 * dialog title, a custom confirmation message, a custom save button
	 * label and a custom cancel button label.
	 * 
	 * @param title
	 * @param confirmMessage
	 * @param saveBtnLabel
	 * @param cancelBtnLabel
	 * @return a basic message dialog with action buttons
	 */
	public static InputDialogFragment newInstance(String title, String confirmMessage,String saveBtnLabel, String cancelBtnLabel){
		if (TextUtils.isEmpty(confirmMessage)) {
			throw new IllegalArgumentException("Missing Confirm message");
		}
		Bundle args=new Bundle();
		args.putString(ARGS_TITLE, title);
		args.putString(ARGS_CONFIRM_MESSAGE, confirmMessage);
		args.putInt(ARGS_CONTENT_RES_ID, R.layout.fragment_message_dialog);
		args.putString(ARGS_SAVE_BTN_LABEL, saveBtnLabel);
		args.putString(ARGS_CANCEL_BTN_LABEL, cancelBtnLabel);
		InputDialogFragment fragment=new InputDialogFragment();
		fragment.setArguments(args);
		return fragment;
	}
	
	/**
	 * This constructor initializes a new input dialog by taking the given
	 * dialog title, and a dialog interface resource id.
	 * 
	 * @param title
	 * @param contentviewResId
	 * @return a basic input dialog
	 */
	public static InputDialogFragment newInstance(String title, int contentviewResId) {
		if (contentviewResId==0) {
			throw new IllegalArgumentException("Missing Content View Resource");
		}
		Bundle args=new Bundle();
		args.putString(ARGS_TITLE, title);
		args.putInt(ARGS_CONTENT_RES_ID, contentviewResId);
		args.putBoolean(ARGS_POSITIVE_BTN_ONLY, true);
		args.putString(ARGS_SAVE_BTN_LABEL, "Ok");
		InputDialogFragment fragment=new InputDialogFragment();
		fragment.setArguments(args);
		return fragment;
	}
	
	/**
	 * This constructor initializes a new input dialog by taking the given
	 * dialog title and a list of selection entries.
	 * 
	 * @param title
	 * @param listEntries
	 * @return a list input dialog
	 */
	public static InputDialogFragment newInstance(String title, String[] listEntries){
		Bundle args=new Bundle();
		args.putString(ARGS_TITLE, title);
		args.putStringArray(ARGS_LIST_ENTRIES, listEntries);
		args.putBoolean(ARGS_LIST_DIALOG,true);
		InputDialogFragment fragment=new InputDialogFragment();
		fragment.setArguments(args);
		return fragment;
	}
	
	/**
	 * A required empty public constructor.
	 */
	public InputDialogFragment() {
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle args=getArguments();
		if (args!=null) {
			_title=args.getString(ARGS_TITLE);
			_isListDialog=args.getBoolean(ARGS_LIST_DIALOG,false);
			if (_isListDialog) {
				_listEntries=args.getStringArray(ARGS_LIST_ENTRIES);
			}else {
				_contentviewResId=args.getInt(ARGS_CONTENT_RES_ID);
				_saveBtnLabel=args.getString(ARGS_SAVE_BTN_LABEL);
				_confirmMessage=args.getString(ARGS_CONFIRM_MESSAGE);
				_cancelBtnLabel=args.getString(ARGS_CANCEL_BTN_LABEL);
				_positiveBtnOnly=args.getBoolean(ARGS_POSITIVE_BTN_ONLY,false);
			}
			
		}
	}
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		// see if we are building a list dialog
		if (_isListDialog) {
			return new AlertDialog.Builder(getSherlockActivity()).setTitle(_title).setItems(_listEntries, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					((OnListItemSelectedListener) getSherlockActivity()).onListItemSelected(which, _listEntries[which]);
				}
			}).create();
		}else {
			//otherwise, inflate the given input interface 
			final View v=LayoutInflater.from(getSherlockActivity()).inflate(_contentviewResId, null);
			//if we are building a message dialog, the interface resource id is already set
			//set the confirmation message
			if (_confirmMessage!=null) {
				((TextView) v.findViewById(R.id.frg_txt_message)).setText(_confirmMessage);
			}
			
			//calls the delegate callback to setup the input interface
			((OnInputListener)getSherlockActivity()).setupInputs(v);
			
			//intialize a new dialog builder to build the dialog
			Builder dialog= new AlertDialog.Builder(getSherlockActivity())
	        .setTitle(Validator.checkNonRequiredNull(_title)?_title:"Input")
	        .setView(v)
	        .setCancelable(true);
			
			//set the save button
	        dialog.setPositiveButton((Validator.checkNonRequiredNull(_saveBtnLabel)?_saveBtnLabel:"Save"), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					if (!_positiveBtnOnly) {
						((OnInputListener) getSherlockActivity()).onInputSaveListener(v);
					}else {
						dialog.cancel();
					}
				}
			});
	        
	        //set the cancel button only if required
	        if (!_positiveBtnOnly) {
	        	dialog.setNegativeButton((Validator.checkNonRequiredNull(_cancelBtnLabel)?_cancelBtnLabel:"Cancel"), new DialogInterface.OnClickListener() {
	                @Override
	                public void onClick(DialogInterface dialog, int which) {
	                    dialog.cancel();
	                }
	            });
			}
	        return dialog.create();
		}
		
		
	}
	
	@Override
	public void onActivityCreated(Bundle arg0) {
		super.onActivityCreated(arg0);
		getDialog().dismiss();
	}
	
	/*@Override
	public void onAttach(Activity activity) {
		getDialog().setTitle(Validator.checkNonRequiredNull(_title)?_title:"Input");
		super.onAttach(activity);
	}*/
}
